package com.pet.chatingRoom.handle;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;

import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.fasterxml.jackson.core.JsonProcessingException;

import com.pet.chatingRoom.config.ClientCache;
import com.pet.service.SysNoticeService;
import com.pet.system.SysNotice;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;


@Slf4j
@Component
public class SocketIOHandler  {
    @Autowired
    SocketIOServer socketIoServer;
    @Autowired
    SysNoticeService sysNoticeService;
    @Autowired
    ClientCache clientCache;
    //测试使用
//    @OnEvent("socketIOHandler")
//    public void testHandler(SocketIOClient client, String data, AckRequest ackRequest) throws JsonProcessingException {
//
//        log.info("SocketIOHandler:{}",data);
//
//        if(ackRequest.isAckRequested()){
//            //返回给客户端，说我接收到了
//            ackRequest.sendAckData("SocketIOHandler",data);
//        }
//
//    }

    @OnEvent("SendMessageToOne")
    public void sendMessageOne(SocketIOClient client, String data, AckRequest ackRequest) throws JsonProcessingException {
        JSONObject jsonObject = JSON.parseObject(data);
        Integer id = (Integer) jsonObject.get("receiveId");
        String message = (String)jsonObject.get("message");
//        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        HashMap<UUID, SocketIOClient> userClient = clientCache.getUserClient(Integer.toString(id));

        //把消息存进数据库
        boolean save = sysNoticeService.save();
        //判断是否在线不在线不转发
        if (userClient==null){
            System.out.println("用户没上线");
            return;
        }
        log.info(data);
        for (UUID sessionId : userClient.keySet()) {
            userClient.get(sessionId).sendEvent("message", message);
            System.out.println(client.getSessionId()+"发消息给"+sessionId);
        }
//            socketIoServer.getNamespace("/socketIO").getClient(sessionId).sendEvent("message", data.substring(5));


    }
    //加入房间
    @OnEvent("joinRoom")
    public void joinRooms(SocketIOClient client, String data, AckRequest ackRequest) throws JsonProcessingException {
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        UUID sessionId = client.getSessionId();
        Map<String, List<String>> urlParams = client.getHandshakeData().getUrlParams();
        for (String s : urlParams.keySet()) {
            System.out.println(s);
        }
        log.info(userId+"加入id");
        log.info(sessionId+"加入sessionId");
        clientCache.saveClient(userId,sessionId,client);
        HashMap<UUID, SocketIOClient> userClient = clientCache.getUserClient(userId);
        for (UUID uuid : userClient.keySet()) {
            System.out.println(uuid+"==="+userClient.get(uuid));
        }
        if(ackRequest.isAckRequested()){
            //返回给客户端，说我接收到了
            ackRequest.sendAckData("加入房间","成功");
        }

    }

    //离开房间
    @OnEvent("leaveRoom")
    public void leaveRoom(SocketIOClient client, String data, AckRequest ackRequest) throws JsonProcessingException {

        client.leaveRoom(data);
        String userId = client.getHandshakeData().getSingleUrlParam("userId");
        clientCache.deleteUserCacheByUserId(userId);
        log.info(userId+"離開房間");
        if(ackRequest.isAckRequested()){
            //返回给客户端，说我接收到了
            ackRequest.sendAckData("离开房间","成功");
        }

    }
    //获取该用户所有房间
    @OnEvent("getUserRooms")
    public void getUserRooms(SocketIOClient client, String data, AckRequest ackRequest) throws JsonProcessingException {

        String userId = client.getHandshakeData().getSingleUrlParam("userId");

        Set<String> allRooms = client.getAllRooms();

        for (String room:allRooms){
            System.out.println("房间名称："+room);
        }

        log.info("服务器收到消息,客户端用户id：{} | 客户发送的消息：{} | 是否需要返回给客户端内容:{} ",userId,data,ackRequest.isAckRequested());


        if(ackRequest.isAckRequested()){
            //返回给客户端，说我接收到了
            ackRequest.sendAckData("消息",data);
        }


    }
    @OnEvent("sendRoomMessage")
    public void sendRoomMessage(SocketIOClient client, String data, AckRequest ackRequest) throws JsonProcessingException {


        String userId = client.getHandshakeData().getSingleUrlParam("userId");


        Set<String> allRooms = client.getAllRooms();

        for (String room:allRooms){
            log.info("房间：{}",room);
            //发送给指定空间名称以及房间的人，并且排除不发给自己
            socketIoServer.getNamespace("/socketIO").getRoomOperations(room).sendEvent("message",client, data);

            //发送给指定空间名称以及房间的人，包括自己
            //socketIoServer.getNamespace("/socketIO").getRoomOperations(room).sendEvent("message", data);;
        }



        if(ackRequest.isAckRequested()){
            //返回给客户端，说我接收到了
            ackRequest.sendAckData("发送消息到指定的房间","成功");
        }

    }
    //广播消息给指定的Namespace下所有客户端
    @OnEvent("sendNamespaceMessage")
    public void sendNamespaceMessage(SocketIOClient client, String data, AckRequest ackRequest) throws JsonProcessingException {


        socketIoServer.getNamespace("/socketIO").getBroadcastOperations().sendEvent("message",client, data);;


        if(ackRequest.isAckRequested()){
            //返回给客户端，说我接收到了
            ackRequest.sendAckData("发送消息到指定的房间","成功");
        }

    }

}
